<template>
  <div class="app-container">
    <el-row :gutter="24" class="mb8">
      <el-col :span="8">
        维度管理
      </el-col>
      <el-col :span="16" style="text-align: right;">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="$router.go(0)"
        >刷新
        </el-button
        >
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="$router.go(-1)"
        >返回
        </el-button
        >
      </el-col>
    </el-row>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>筛选列表</span>
      </div>
      <div class="text item">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          label-width="100px"
        >
          <el-form-item label="科目：" prop="subjectId">
            <el-select
              v-model="queryParams.subjectId"
              placeholder="请选择科目"
              clearable
              size="small"
            >
              <el-option
                v-for="(item, index) in subjectList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="维度名称：" prop="dimensionName">
            <el-input v-model="queryParams.dimensionName" placeholder="请输入维度名称"/>
          </el-form-item>
          <el-form-item label="编号：" prop="sortNum">
            <el-input v-model="queryParams.sortNum" placeholder="请输入编号"/>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            >搜索
            </el-button
            >
            <el-button
              type="primary"
              icon="el-icon-refresh"
              size="mini"
              @click="resetQuery"
            >重置
            </el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>维度列表</span>

        <el-button
          type="primary"
          size="mini"
          style="float: right; margin-left: 10px;"
          @click="handleExport"
        >导出数据
        </el-button>
        <el-button
          type="primary"
          size="mini"
          style="float: right;"
          @click="handleImport"
        >导入EXCEL
        </el-button>
        <el-button
          type="primary"
          size="mini"
          style="float: right;"
          @click="handleExportModel"
        >下载模板
        </el-button>
        <el-button
          type="primary"
          size="mini"
          style="float: right;"
          @click="batchDelete"
        >批量删除
        </el-button>
        <el-button
          type="primary"
          size="mini"
          style="float: right;"
          @click="handleAdd"
        >新增
        </el-button>
      </div>
      <div class="text item">
        <el-table v-loading="loading" :data="tableList"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="编号" align="center" prop="sortNum"/>
          <el-table-column label="维度名称" align="center" prop="dimensionName"/>
          <el-table-column label="卷面上的题号" align="center" prop="questionIndex"/>
          <el-table-column label="科目ID" align="center" prop="subjectName"/>
          <el-table-column label="关联科目ID" align="center" prop="subjectRealtionName"/>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                class="btn_close"
                @click="handleDelete(scope.row.uuid)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 新增、修改维度配置对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      :before-close="cancel"
      width="520px"
      :close-on-click-modal="true"
      append-to-body
    >
      <el-form ref="editFormRef" :model="formData" :rules="formRules" label-width="110px">
        <el-form-item label="维度名称" prop="dimensionName">
          <el-input v-model="formData.dimensionName" placeholder="请输入维度名称"/>
        </el-form-item>
        <el-form-item label="编号" prop="sortNum">
          <el-input
            v-model="formData.sortNum"
            placeholder="请输入编号"
            @input="onInputValue"
          />
        </el-form-item>
        <el-form-item label="卷面上的题号" prop="questionIndex">
          <el-input v-model="formData.questionIndex" placeholder="请输入卷面上的题号"/>
        </el-form-item>
        <el-form-item label="科目" prop="subjectId">
          <el-select
            v-model="formData.subjectId"
            placeholder="请选择科目"
            clearable
            size="small"
          >
            <el-option
              v-for="(item, index) in subjectList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="关联科目" prop="subjectRelationId">
          <el-select
            v-model="formData.subjectRelationId"
            placeholder="请选择关联科目"
            clearable
            size="small"
          >
            <el-option
              v-for="(item, index) in subjectList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 维度导入对话框 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      :before-close="cancelFileForm"
      append-to-body>
      <el-upload
        ref="upload"
        name="multipartFile"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="cancelFileForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    getSubjectList,
    getDimensionList,
    addDimension,
    uploadDimension,
    removeDimension,
    getDimensionInfo
  } from "@/api/toolsystem/DQgroup";
  import {getToken} from "@/utils/auth";

  export default {
    name: "dimension",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          subjectId: null,
          dimensionName: null,
          sortNum: null,
        },
        subjectList: [],// 筛选-科目列表
        tableList: [], // 表格数据-维度列表
        total: 0, // 总条数
        uuids: [],// 批量-选中的uuid集合
        title: "",// 弹出层标题
        open: false,// 是否显示弹出层
        // 新增/修改表单参数
        formData: {
          dimensionName: null,
          questionIndex: null,
          sortNum: null,
          subjectId: null,
          subjectRelationId: null,
        },
        formRules: {
          dimensionName: [
            {
              required: true,
              message: "请输入维度名称",
              trigger: "blur"
            }
          ],
          questionIndex: [
            {
              required: true,
              message: "请输入卷面上的题号",
              trigger: "blur"
            }
          ],
          sortNum: [
            {
              required: true,
              message: "请输入编号",
              trigger: "blur"
            }
          ],
          subjectId: [
            {
              required: true,
              message: "请选择科目",
              trigger: "change"
            }
          ],
          subjectRelationId: [
            {
              required: true,
              message: "请选择关联科目",
              trigger: "change"
            }
          ],
        }, // 表单校验
        isChecked: false, // 防重复点击
        // 维度导入参数
        upload: {
          // 是否显示弹出层（维度导入）
          open: false,
          // 弹出层标题（维度导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: {Authorization: "Bearer " + getToken()},
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/after-exam-score/thDimensionQuestion/import"
        },
      };
    },
    created() {
      this.getSubjects();
      this.getList();
    },
    methods: {
      onInputValue(val) {
        this.formData.sortNum = val.replace(/[^a-zA-Z\d]/g, '');
      },
      /** 筛选表单重置 */
      resetQuery() {
        this.$refs["queryForm"].resetFields()
        this.getList();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 查询维度配置列表 */
      getList() {
        this.loading = true;
        getDimensionList(this.queryParams)
          .then(response => {
            if (response.code != 200) {
              this.loading = false;
              return this.msgError(response.msg);
            }
            this.tableList = response.rows;
            this.total = response.total;
            this.loading = false;
          })
          .catch(error => {
            this.loading = false;
            console.log(error);
          });
      },
      /** 获取科目列表 */
      getSubjects() {
        getSubjectList()
          .then(response => {
            console.log(response)
            if (response.code != 200) {
              return this.msgError(response.msg);
            }
            this.subjectList = response.rows;
          })
          .catch(error => {
            console.log(error);
          });
      },
      /** 删除按钮操作 */
      handleDelete(uuid) {
        const uuids = uuid;
        this.$confirm(
          '是否确认删除该数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(() => {
            removeDimension(uuids).then(response => {
              console.log(response);
              if (response.code != 200) {
                return this.msgError(response.msg);
              }
              this.getList();
              this.msgSuccess(response.msg);
            });
          })
          .catch(() => {
            this.msgInfo("取消删除");
          });
      },
      /** 批量删除 */
      batchDelete() {
        if (this.uuids.length <= 0) {
          return this.msgInfo("请选择需要删除的维度");
        }
        this.handleDelete(this.uuids.join(","));
      },
      /** 多选框选中数据 */
      handleSelectionChange(selection) {
        this.uuids = selection.map(item => item.uuid);
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.formData = row;
        this.open = true;
        this.title = "修改维度配置";
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.open = true;
        this.title = "新增维度配置";
      },
      /** 取消按钮 */
      cancel() {
        this.open = false;
        this.formData = {
          dimensionName: null,
          questionIndex: null,
          sortNum: null,
          subjectId: null,
          subjectRelationId: null,
        }
        this.$refs["editFormRef"].resetFields();
      },
      /** 新增、修改弹框提交按钮 */
      submitForm() {
        if (this.isChecked) {
          return;
        }
        this.isChecked = true;
        this.$refs["editFormRef"].validate(valid => {
          if (!valid) return this.isChecked = false;
          if (this.title.indexOf('修改') != -1) {
            // 修改
            uploadDimension(this.formData)
              .then(response => {
                if (response.code != 200) {
                  this.msgError(response.msg);
                  return this.isChecked = false;
                }
                this.msgSuccess(response.msg);
                this.cancel();
                this.getList();
                this.isChecked = false
              })
              .catch(error => {
                this.isChecked = false;
                console.log(error);
              });
          } else {
            // 新增
            addDimension(this.formData)
              .then(response => {
                console.log(response);
                if (response.code != 200) {
                  this.msgError(response.msg)
                  return this.isChecked = false
                }
                this.msgSuccess(response.msg);
                this.cancel();
                this.handleQuery();
                this.isChecked = false
              })
              .catch(error => {
                this.isChecked = false
                console.log(error)
              });
          }
        });
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "维度导入";
        this.upload.open = true;
      },
      /** 文件上传中处理 */
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      /** 文件上传成功处理 */
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        if(response.code != 200){
          this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
          return;
        }
        this.msgSuccess(response.msg)
        this.getList();
      },
      /** 提交上传文件 */
      submitFileForm() {
        this.$refs.upload.submit();
      },
      /** 取消上传文件 */
      cancelFileForm(){
        this.$refs.upload.clearFiles();
        this.upload.open = false
      },
      /** 下载模板操作 */
      handleExportModel(){
        this.download(
          "after-exam-score/thDimensionQuestion/exportExcelModel",
          {},
          `维度列表.xlsx`
        );
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download(
          "after-exam-score/thDimensionQuestion/export",
          // {...this.queryParams},
          {},
          `维度列表.xlsx`
        );
      }
    }
  };
</script>

<style lang="scss">
  @import "@/assets/styles/card.scss";
  @import "@/assets/styles/dialog.scss";
</style>
